package com.example.kotlineventtracker.view

import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.kotlineventtracker.EventInfoActivity
import com.example.kotlineventtracker.PageActivity
import com.example.kotlineventtracker.databinding.ItemPageEventBinding
import com.example.kotlineventtracker.model.PageEvent

class EventAdapter(private val events: List<PageEvent>, private val type: String) :
    RecyclerView.Adapter<EventAdapter.EventViewHolder>() {

    class EventViewHolder(private val binding: ItemPageEventBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(event: PageEvent, type: String) {
            when (type) {
                "page" -> {
                    binding.id.text = "页面ID: ${event.pageId}"
                    binding.desc.text = "页面名称: ${event.pageDesc}"
                    binding.eventTypeStr.text = "事件类型: ${event.eventTypeStr}"
                    binding.owner.text = "管理员: ${event.owner}"
                    binding.moduleNum.text = "模块数量: ${event.moduleNum}"

                    binding.detailButton.setOnClickListener {
                        val context = binding.root.context
                        val intent = Intent(context, PageActivity::class.java)
                        intent.putExtra("pageId", event.pageId)
                        intent.putExtra("pageDesc", event.pageDesc)
                        context.startActivity(intent)
                    }
                }
                "module" -> {
                    binding.id.text = "模块ID: ${event.moduleId}"
                    binding.desc.text = "模块名称: ${event.moduleDesc}"
                    binding.eventTypeStr.text = "事件类型: ${event.eventTypeStr}"
                    binding.owner.text = "管理员: ${event.owner}"

                    binding.detailButton.setOnClickListener {
                        val context = binding.root.context
                        val intent = Intent(context, EventInfoActivity::class.java)
                        intent.putExtra("eventId", event.moduleId)
                        intent.putExtra("moduleDesc", event.moduleDesc)
                        intent.putExtra("eventType",event.moduleEventType[0])
                        context.startActivity(intent)
                    }
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EventViewHolder {
        val binding = ItemPageEventBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
        return EventViewHolder(binding)
    }

    override fun onBindViewHolder(holder: EventViewHolder, position: Int) {
        holder.bind(events[position], type)
    }

    override fun getItemCount() = events.size
}